package com.ruoyi.management.service.impl;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.ruoyi.management.domain.Bx;
import com.ruoyi.management.mapper.BxMapper;
import com.ruoyi.management.service.StatisService;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class StatisServiceImpl implements StatisService {
    @Autowired
    private BxMapper bxMapper;

    @Value("${uploadfpUrl}")
    private String uploadfpUrl;

    @Value("${uploadfpUrlhttp}")
    private String uploadfpUrlhttp;

    @Override
    public String statisPdfList(Bx bx) throws IOException {
        List<Bx> list =  bxMapper.selectCcsqLisGroupbyXmid(bx);
        PDFMergerUtility pdfMerger = new PDFMergerUtility();
        //判断单个多个
        List<Bx> newList = new ArrayList<>();
        for (Bx bx1 : list){
            String path = bx1.getAddress();
            if(path.indexOf(";") != -1){
                //分割
                String[] fruits = path.split(";");
                for (String o:fruits){
                    bx1.setAddress(o);
                    newList.add(bx1);
                }
            }else {
                newList.add(bx1);
            }
        }
        System.out.println(newList);

        // 确保输出目录存在
        File outputDir = new File(uploadfpUrl);
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        //生成唯一的输出文件名
        String mergedFileName = "merged_" + System.currentTimeMillis() + ".pdf";
        String outputPath = uploadfpUrl + File.separator + mergedFileName;
        pdfMerger.setDestinationFileName(outputPath);

        mergePdfFiles(newList, outputPath);
        Path path = Paths.get(outputPath);
        return uploadfpUrlhttp + path.getFileName();
    }

    public void mergePdfFiles(List<Bx> pdfFiles, String outputPath) {
        Document document = new Document();
        try {
            // 创建PdfCopy对象
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(outputPath));
            document.open();
            // 遍历所有PDF文件
            for (Bx pdfFile : pdfFiles) {
                String pdfaa = pdfFile.getAddress();
                if( !pdfaa.isEmpty() && pdfaa!= null) {
                    String filepdfUrl = uploadfpUrl + '/' + pdfFile.getAddress();
                    PdfReader reader = new PdfReader(filepdfUrl);
                    int numberOfPages = reader.getNumberOfPages();
                    // 逐页添加到合并文件中
                    for (int page = 1; page <= numberOfPages; page++) {
                        copy.addPage(copy.getImportedPage(reader, page));
                    }

                    reader.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document.isOpen()) {
                document.close();
            }
        }
    }
}
